package edu.whu.powersoap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.navisdk.BNaviModuleManager;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.comapi.mapcontrol.BNMapController;
import com.baidu.navisdk.comapi.routeplan.BNRoutePlaner;
import com.baidu.navisdk.comapi.tts.BNTTSPlayer;
import com.baidu.navisdk.comapi.tts.BNavigatorTTSPlayer;
import com.baidu.navisdk.comapi.tts.IBNTTSPlayerListener;
import com.baidu.navisdk.model.datastruct.LocData;
import com.baidu.navisdk.model.datastruct.SensorData;
import com.baidu.navisdk.ui.routeguide.BNavigator;
import com.baidu.navisdk.ui.routeguide.IBNavigatorListener;
import com.baidu.navisdk.ui.widget.RoutePlanObserver;
import com.baidu.navisdk.ui.widget.RoutePlanObserver.IJumpToDownloadListener;
import com.baidu.nplatform.comapi.map.MapGLSurfaceView;

import edu.whu.powersoap.BNavigatorActivity.MyLocationListenner;

public class BNavigatorActivity extends Activity{
	private final static String TAG = "BNavigatorActivity";
	private LayoutInflater mLayoutInflater;
	private BDLocation mLocation;
	private Context mContext;
	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListenner();
	private LocationClient mLocClient;
	private String localPoi;
	private String pt2;	
	private int flag = 0;
	private Dialog dialogm;
	private String number;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg){
			Log.i(TAG, "handleMessage start.....");
			Double a = mLocation.getLatitude();
        	Double b = mLocation.getLongitude();
        	localPoi = String.valueOf(a)+ ";" + String.valueOf(b);
        	Intent intent = getIntent();
        	number = intent.getStringExtra("number");
    		pt2 = intent.getStringExtra("pospt2");
    		String[] pospt1 = localPoi.split(";");
    		String[] pospt2 = pt2.split(";");
    		onArriveDestNear(pospt1, pospt2);
        	Log.i(TAG, "latlat=" + String.valueOf(a) + ", lonlon=" + String.valueOf(b));
        	super.handleMessage(msg);
		}
	};
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		mLayoutInflater = LayoutInflater.from(this);
		mContext = BNavigatorActivity.this;
		//创建NmapView
		if (Build.VERSION.SDK_INT < 14) {
            BaiduNaviManager.getInstance().destroyNMapView();
        }
		MapGLSurfaceView nMapView = BaiduNaviManager.getInstance().createNMapView(this);
		
		//创建导航视图
		View navigatorView = BNavigator.getInstance().init(BNavigatorActivity.this, getIntent().getExtras(), nMapView);
		
		mLocClient = new LocationClient(this);
		mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		// option.setPriority(LocationClientOption.NetWorkFirst);
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();
		
		//填充视图
		setContentView(navigatorView);
		BNavigator.getInstance().setListener(mBNavigatorListener);
		BNavigator.getInstance().startNav();
		
//		Intent intent = getIntent();
//		pt2 = intent.getStringExtra("pospt2");
	   
		
		
		// 初始化TTS. 开发者也可以使用独立TTS模块，不用使用导航SDK提供的TTS
		BNTTSPlayer.initPlayer();
		//设置TTS播放回调
		BNavigatorTTSPlayer.setTTSPlayerListener(new IBNTTSPlayerListener() {
            
            @Override
            public int playTTSText(String arg0, int arg1) {
            	//开发者可以使用其他TTS的API
                return BNTTSPlayer.playTTSText(arg0, arg1);
            }
            
            @Override
            public void phoneHangUp() {
                //手机挂断
            }
            
            @Override
            public void phoneCalling() {
                //通话中
            }
            
            @Override
            public int getTTSState() {
            	//开发者可以使用其他TTS的API,
                return BNTTSPlayer.getTTSState();
            }
        });
		
		BNRoutePlaner.getInstance().setObserver(new RoutePlanObserver(this, new IJumpToDownloadListener() {
			
			@Override
			public void onJumpToDownloadOfflineData() {
				// TODO Auto-generated method stub
				
			}
		}));
		
	}
	
	private IBNavigatorListener mBNavigatorListener = new IBNavigatorListener() {
        
        @Override
        public void onYawingRequestSuccess() {
            // TODO 偏航请求成功
            
        }
        
        @Override
        public void onYawingRequestStart() {
            // TODO 开始偏航请求
            
        }
        
        @Override
        public void onPageJump(int jumpTiming, Object arg) {
            // TODO 页面跳转回调
        	if(IBNavigatorListener.PAGE_JUMP_WHEN_GUIDE_END == jumpTiming){
        	    finish();
        	}else if(IBNavigatorListener.PAGE_JUMP_WHEN_ROUTE_PLAN_FAIL == jumpTiming){
        		finish();
        	}
        }

		@Override
		public void notifyGPSStatusData(int arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void notifyLoacteData(LocData arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void notifyNmeaData(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void notifySensorData(SensorData arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void notifyStartNav() {
			// TODO Auto-generated method stub
			BaiduNaviManager.getInstance().dismissWaitProgressDialog();
		}

		@Override
		public void notifyViewModeChanged(int arg0) {
			// TODO Auto-generated method stub
			
		}
        
    };
	    
	@Override
    public void onResume() {
        BNavigator.getInstance().resume();
        super.onResume();
        BNMapController.getInstance().onResume();
    };

    @Override
    public void onPause() {
        BNavigator.getInstance().pause();
        super.onPause();
        BNMapController.getInstance().onPause();
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	BNavigator.getInstance().onConfigurationChanged(newConfig);
        super.onConfigurationChanged(newConfig);
    }
    
    public void onBackPressed(){
        BNavigator.getInstance().onBackPressed();
    }
    
    @Override
    public void onDestroy(){
    	BNavigator.destory();
		BNRoutePlaner.getInstance().setObserver(null);
    	super.onDestroy();
    }
    
            
    public void onArriveDestNear(String[] pospt1, String[] pospt2){
    	Log.i(TAG, "the distance is " +distance(pospt1, pospt2) + "");
		if(distance(pospt1, pospt2) < 10000 && flag==0){
			BNavigator.getInstance().pause();		
	    	final View markView = mLayoutInflater
					.inflate(R.layout.mark, null);
			String mark = "marked";		            
            ContentValues values = new ContentValues();	
            ContentResolver cr = mContext.getContentResolver(); 
            values.put(MarkProvider.VOLUMN_NUMBER, number);
            values.put(MarkProvider.VOLUMN_FLAG, mark);	            
            cr.insert(MarkProvider.CONTENT_URI, values);
            
			dialogm = new AlertDialog.Builder(BNavigatorActivity.this)
			.setView(markView)
			.setTitle("Mark Message")
			.setPositiveButton("确认",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog,
								int which) {
							dialog.dismiss();
							BNavigator.getInstance().resume();
						}
					}).create();

			dialogm.show();
			
			
			Button btn1,btn2,btn3,btn4;
			CheckBox check;
			check = (CheckBox)markView.findViewById(R.id.check);					
//			btn0 = (Button) markView.findViewById(R.id.btn_noneed);
			btn1 = (Button) markView.findViewById(R.id.btn_word);
			btn2 = (Button) markView.findViewById(R.id.btn_photo);
			btn3 = (Button) markView.findViewById(R.id.btn_video);
			btn4 = (Button) markView.findViewById(R.id.btn_voice);
			
			check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){ 
	            @Override 
	            public void onCheckedChanged(CompoundButton buttonView, 
	                    boolean isChecked) { 
	                // TODO Auto-generated method stub 
	                if(isChecked){ 
	                	Dialog dialog = new AlertDialog.Builder(BNavigatorActivity.this)
						.setMessage("无需记录任何信息")
						.setTitle("提示")
						.setNegativeButton("取消", new DialogInterface.OnClickListener(){

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								dialogm.dismiss();
								
								
							}
							
						})
						.setPositiveButton("确认",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										String mark = "unmarked";
										ContentValues values = new ContentValues();	 				            
							            values.put(MarkProvider.VOLUMN_FLAG, mark);
										ContentResolver cr = mContext.getContentResolver();
										cr.update(MarkProvider.CONTENT_URI, values, "number =?", new String[]{number});
										dialog.dismiss();
										dialogm.dismiss();
//											BNavigatorActivity.this.finish();
									}
								}).create();
				dialog.show();	
	                }else{ 
	                	dialogm.dismiss();
	                } 
	            } 
	        });

			btn1.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					final View wordView = mLayoutInflater
							.inflate(R.layout.mark_word, null);
					
		            
		            Dialog dialog = new AlertDialog.Builder(BNavigatorActivity.this)
		            					.setView(wordView)
		            					.setNegativeButton("取消", new DialogInterface.OnClickListener(){

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {												
												dialog.dismiss();
//												dialogm.dismiss();
												
											}
		            					
		            					})
		            					.setPositiveButton("确定记录", 
		            							new DialogInterface.OnClickListener(){

													@Override
													public void onClick(
															DialogInterface dialog,
															int which) {
											            EditText word = (EditText) wordView.findViewById(R.id.mark_word);
														ContentValues values = new ContentValues();													
														ContentResolver cr = mContext.getContentResolver();          
											            Cursor c = cr.query(MarkProvider.CONTENT_URI, new String[] 
																{
																MarkProvider.VOLUMN_NUMBER + " as _id",
																MarkProvider.VOLUMN_WORD 
																}, "number =?", new String[]{number}, null);
											            c.moveToFirst();
														int id = c.getColumnIndex(MarkProvider.VOLUMN_WORD);
														String o_word = c.getString(id);
														c.close();
														String n_word = null;
														if(o_word==null){							
															n_word = word.getText().toString();
														}else{
															n_word = o_word + " ; "+word.getText().toString();
														}																												
											            values.put(MarkProvider.VOLUMN_WORD, n_word);
											            values.put(MarkProvider.VOLUMN_FLAG, "marked");
														cr.update(MarkProvider.CONTENT_URI, values, "number =?", new String[]{number});
														
														dialog.dismiss();
//														dialogm.dismiss();
													}
		            						
		            					}).create();
		            
		            dialog.show();
				}
				
			});
			
			btn2.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					 Intent it = new Intent(BNavigatorActivity.this, MyCameraActivity.class);
					 Bundle bundle = new Bundle();
					 bundle.putString("number", number);
					 it.putExtras(bundle);
					 startActivity(it); 
//					 dialogm.dismiss();
					
				}
				
			});
			
			btn3.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Intent it = new Intent(BNavigatorActivity.this, MyVideoActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("number", number);
					it.putExtras(bundle);
					startActivity(it); 
//					dialogm.dismiss();
					
				}
				
			});
			
			btn4.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View v) {
						Intent it = new Intent(BNavigatorActivity.this, MyVoiceActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("number", number);
						it.putExtras(bundle);
						startActivity(it); 
//						dialogm.dismiss();																										
					}						
				});	
		}else {
//			BNavigator.getInstance().pause();
		}
		flag ++;
	}
	
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mLocation = location;
			
			handler.sendMessage(handler.obtainMessage(1));
		}
	}

	
	public double distance(String[] a , String[] b){
		double lat1 = Double.parseDouble(a[0]);
		double lng1 = Double.parseDouble(a[1]);
		double lat2 = Double.parseDouble(b[0]);
		double lng2 = Double.parseDouble(b[1]);
		double radLat1 = lat1 * Math.PI / 180;
		double radLat2 = lat2 * Math.PI / 180;
		double aa = radLat1 - radLat2;
		double bb = lng1 * Math.PI / 180 - lng2 * Math.PI / 180;
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(aa / 2), 2)
		+ Math.cos(radLat1) * Math.cos(radLat2)
		* Math.pow(Math.sin(bb / 2), 2)));
		s = s * 6378137.0;
		s = Math.round(s * 10000) / 10000;
		return s;	
	}
}
